package com.topcent.tioxyc.controller;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.topcent.tioxyc.constants.KeyConstant;
import com.topcent.tioxyc.mapper.Yy1KpiMapper;
import com.topcent.tioxyc.pojo.*;
import com.topcent.tioxyc.util.ApiClient;
import com.topcent.tioxyc.util.ConnmeUtils;
import com.topcent.tioxyc.util.PurchaseCommunity;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.Header;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/**
 * @author: weidian
 * @date: 2024/11/20 15:32
 * @Description: 销售和销货单数据统计
 */
@Slf4j
@RestController
public class StatisticsController {

    @Autowired
    private Yy1KpiMapper yy1KpiMapper;

    @GetMapping("/statistics")
    public String statistics() {
        Header[] headers = ConnmeUtils.createHeaders();
        List<SalesReport> salesDeliveryReport = yy1KpiMapper.getSalesDeliveryReport();
        for (SalesReport salesReport : salesDeliveryReport) {
            Map<String, Object> shenqing = new HashMap<>();
            shenqing.put("app_id", "673d3a89b8c968a31b8425b6");
            shenqing.put("entry_id", "673d3e9f49d2ac8c11cbe186");
            HashMap<String, String > shenqingdan=new HashMap<>();
            shenqingdan.put("month",salesReport.getMonth());
            shenqingdan.put("department_name",salesReport.getDepartment_name());
            List<SalesReport> salesReports = PurchaseCommunity.queryBased(shenqing, headers, shenqingdan, SalesReport.class);
            if (!salesReports.isEmpty()){
                xiu(salesReport);
            }else {
                xiao(salesReport, "673d3e9f49d2ac8c11cbe186");
            }

        }
        List<SalesReport> salesOrderReport = yy1KpiMapper.getSalesOrderReport();
        for (SalesReport salesReport : salesOrderReport) {
            Map<String, Object> shenqing = new HashMap<>();
            shenqing.put("app_id", "673d3a89b8c968a31b8425b6");
            shenqing.put("entry_id", "673d3f4630fbad8dee23beda");
            HashMap<String, String > shenqingdan=new HashMap<>();
            shenqingdan.put("month",salesReport.getMonth());
            shenqingdan.put("department_name",salesReport.getDepartment_name());
            List<SalesReport> salesReports = PurchaseCommunity.queryBased(shenqing, headers, shenqingdan, SalesReport.class);
            if (!salesReports.isEmpty()){
                xiu(salesReport);
            }else {
                xiao(salesReport, "673d3f4630fbad8dee23beda");
            }

        }

        List<MonthlyCustomerStatistics> monthlyCustomerStatistics = yy1KpiMapper.get_monthly_customer_statistics();
        for (MonthlyCustomerStatistics monthlyCustomerStatistics1 : monthlyCustomerStatistics) {
            Map<String, Object> shenqing = new HashMap<>();
            shenqing.put("app_id", "673d3a89b8c968a31b8425b6");
            shenqing.put("entry_id", "673d3ef705749c10369c45af");
            HashMap<String, String > shenqingdan=new HashMap<>();
            shenqingdan.put("month",monthlyCustomerStatistics1.getMonth());
            shenqingdan.put("department_name",monthlyCustomerStatistics1.getDepartment_name());
            List<MonthlyCustomerStatistics> customerStatistics = PurchaseCommunity.queryBased(shenqing, headers, shenqingdan, MonthlyCustomerStatistics.class);
            if (!customerStatistics.isEmpty()){
                xiu(monthlyCustomerStatistics1);
            }else {
                xiao(monthlyCustomerStatistics1);
            }

        }

        List<DeliveryData> latestDeliveryData = yy1KpiMapper.getLatestDeliveryData();
        for (DeliveryData latestDeliveryDatum : latestDeliveryData) {
            Map<String, Object> shenqing = new HashMap<>();
            shenqing.put("app_id", "667230ad22a8581756b77d52");
            shenqing.put("entry_id", "667230b322a8581756b78353");
            HashMap<String, String > shenqingdan=new HashMap<>();
            shenqingdan.put("_widget_1718759603973",latestDeliveryDatum.getSalesDocument());
            List<SalesOrder> salesOrders = PurchaseCommunity.queryBased(shenqing, headers, shenqingdan, SalesOrder.class);
            if (!salesOrders.isEmpty()){
                int i = 0;
                salesOrders.sort(Comparator.comparing(SalesOrder::getCreateTime).reversed());
                for (SalesOrder salesOrder : salesOrders) {
                    if (salesOrder.getFlowState()==1){
                        break;
                    }else {
                        i++;
                    }
                }
                String now = DateUtil.now();
                Date date = DateUtil.parse(now);
                long betweenDay = DateUtil.between(salesOrders.get(i).getReview_date(), date, DateUnit.DAY);
                if (betweenDay==0 || salesOrders.get(i).get_widget_1718759603988()==null){
                    continue;
                }

                DateTime widget1718759603988 = salesOrders.get(i).get_widget_1718759603988();
                DateTime dateTime = DateUtil.offsetDay(widget1718759603988, 20);
                String deliveryDate = latestDeliveryDatum.getDeliveryDate();
                DateTime tese = DateUtil.parse(deliveryDate);
                boolean before = dateTime.isBefore(tese);

                // 查询部门是否已经存在，有就修改，没有就新增
                Map<String, Object> shenqings = new HashMap<>();
                shenqings.put("app_id", "673d3a89b8c968a31b8425b6");
                shenqings.put("entry_id", "673d3cd90c0215e9410a074a");
                HashMap<String, String > shenqingdans=new HashMap<>();
                shenqingdans.put("_widget_1732066539301",latestDeliveryDatum.getMonth());
                String jsonString = JSONUtil.toJsonStr(salesOrders.get(i).get_widget_1718759603978());
                JSONObject jsonObject = JSONUtil.parseObj(jsonString);

                shenqingdans.put("_widget_1732065938724",jsonObject.getStr("name"));
                List<DeliveryStatistics> deliveryStatisticsList = PurchaseCommunity.queryBased(shenqings, headers, shenqingdans, DeliveryStatistics.class);

                if (!deliveryStatisticsList.isEmpty()){
                    DeliveryStatistics first = deliveryStatisticsList.getFirst();
                    if (before){
                        first.set_widget_1732066539302(first.get_widget_1732066539302()+1);
                    }else {
                        first.set_widget_1732065938725(first.get_widget_1732065938725()+1);
                    }
                    xiu(first);
                }else {
                    DeliveryStatistics first =  new DeliveryStatistics();
                    first.set_widget_1732065938724(jsonObject.getStr("name"));
                    first.set_widget_1732066539301(latestDeliveryDatum.getMonth());
                    if (before){
                        first.set_widget_1732066539302(1);
                        first.set_widget_1732065938725(0);
                    }else {
                        first.set_widget_1732065938725(1);
                        first.set_widget_1732066539302(0);
                    }
                    xiao(first);
                }
            }
        }




        return "sett";
    }

    private static void xiao(SalesReport salesReport, String eid) {
        Header[] headers = ConnmeUtils.createHeaders();
        Map<String, Object> parameter = new HashMap<>();
        parameter.put("app_id", "673d3a89b8c968a31b8425b6");
        parameter.put("entry_id", eid);
        parameter.put("data", ConnmeUtils.convertEntityToMap(salesReport));
        salesReport.set_id(null);
        String jsonSale = JSONUtil.toJsonStr(parameter);
        log.info("销货单统计的数据：==== {}", jsonSale);
        JSONObject jdySale = ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/app/entry/data/create", headers, jsonSale);
    }
    private static void xiu(SalesReport salesReport) {
        Header[] headers = ConnmeUtils.createHeaders();
        Map<String, Object> parameterInsters = new HashMap<>();
        parameterInsters.put("app_id", "673d3a89b8c968a31b8425b6");
        parameterInsters.put("entry_id", "673d3e9f49d2ac8c11cbe186");
        parameterInsters.put("is_start_trigger", "true");
        parameterInsters.put("data_id", salesReport.get_id());
        salesReport.set_id(null);
        parameterInsters.put("data", ConnmeUtils.convertEntityToMapNull(salesReport));
        String jsonSalees = JSONUtil.toJsonStr(parameterInsters);
        ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/app/entry/data/update", headers, jsonSalees);
    }

    private static void xiao(MonthlyCustomerStatistics salesReport) {
        Header[] headers = ConnmeUtils.createHeaders();
        Map<String, Object> parameter = new HashMap<>();
        parameter.put("app_id", "673d3a89b8c968a31b8425b6");
        parameter.put("entry_id", "673d3ef705749c10369c45af");
        parameter.put("data", ConnmeUtils.convertEntityToMap(salesReport));
        salesReport.set_id(null);
        String jsonSale = JSONUtil.toJsonStr(parameter);
        log.info("销货单统计的数据：==== {}", jsonSale);
        JSONObject jdySale = ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/app/entry/data/create", headers, jsonSale);
    }
    private static void xiu(MonthlyCustomerStatistics monthlyCustomerStatistics) {
        Header[] headers = ConnmeUtils.createHeaders();
        Map<String, Object> parameterInsters = new HashMap<>();
        parameterInsters.put("app_id", "673d3a89b8c968a31b8425b6");
        parameterInsters.put("entry_id", "673d3e9f49d2ac8c11cbe186");
        parameterInsters.put("is_start_trigger", "true");
        parameterInsters.put("data_id", monthlyCustomerStatistics.get_id());
        monthlyCustomerStatistics.set_id(null);
        parameterInsters.put("data", ConnmeUtils.convertEntityToMapNull(monthlyCustomerStatistics));
        String jsonSalees = JSONUtil.toJsonStr(parameterInsters);
        ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/app/entry/data/update", headers, jsonSalees);
    }

    private static void xiu(DeliveryStatistics deliveryStatistics) {
        Header[] headers = ConnmeUtils.createHeaders();
        Map<String, Object> parameterInsters = new HashMap<>();
        parameterInsters.put("app_id", "673d3a89b8c968a31b8425b6");
        parameterInsters.put("entry_id", "673d3cd90c0215e9410a074a");
        parameterInsters.put("is_start_trigger", "true");
        parameterInsters.put("data_id", deliveryStatistics.get_id());
        deliveryStatistics.set_id(null);
        parameterInsters.put("data", ConnmeUtils.convertEntityToMapNull(deliveryStatistics));
        String jsonSalees = JSONUtil.toJsonStr(parameterInsters);
        ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/app/entry/data/update", headers, jsonSalees);
    }
    private static void xiao(DeliveryStatistics salesReport) {
        Header[] headers = ConnmeUtils.createHeaders();
        Map<String, Object> parameter = new HashMap<>();
        parameter.put("app_id", "673d3a89b8c968a31b8425b6");
        parameter.put("entry_id", "673d3cd90c0215e9410a074a");
        parameter.put("data", ConnmeUtils.convertEntityToMap(salesReport));
        salesReport.set_id(null);
        String jsonSale = JSONUtil.toJsonStr(parameter);
        log.info("销货单统计的数据：==== {}", jsonSale);
        JSONObject jdySale = ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/app/entry/data/create", headers, jsonSale);
    }
}
